package com.jkt.rms.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.web.servlet.ModelAndView;

import com.jkt.rms.businessservice.RateBusinessService;
import com.jkt.rms.cache.RMSCache;
import com.jkt.rms.commons.utils.RMSException;
import com.jkt.rms.commons.utils.ServiceLocator;
import com.jkt.rms.vo.RateVO;

public class RateController extends AbstractMultiActionController {

	private final static Logger LOG = Logger.getLogger(RateController.class);
	private RateBusinessService rateBusinessService = ServiceLocator
			.getServiceLocator().locate("rateBusinessService");
	RMSCache cache = ServiceLocator.getServiceLocator().locate("cacheService");
	 
	public ModelAndView addRate(HttpServletRequest request,
			HttpServletResponse response, RateVO rateVO) throws RMSException {
		LOG.info("===addRate()===");
		validate(rateVO);		
		if (errors != null && errors.getAllErrors() != null
				&& errors.getAllErrors().size() > 0) {
			loadInitData(rateVO);
			return new ModelAndView("searchAddRate", "rateBean", rateVO).addObject("errors", errors);
		} else {
			// Handle the business code
			try {
				rateBusinessService.addRate(rateVO);
				rateVO = new RateVO();
				rateVO.setMessage("rate.add.success");
			} catch (RMSException e) {
				rateVO.setMessage(e.getBusinessCode());
			}finally{				
				loadInitData(rateVO);
			}
			return new ModelAndView("searchAddRate", "rateBean", rateVO);
		}

	}

	public ModelAndView loadRate(HttpServletRequest request,
			HttpServletResponse response) throws RMSException {
		LOG.info("===loadRate()===");
		RateVO rateVO = new RateVO();
		loadInitData(rateVO);
		return new ModelAndView("searchAddRate", "rateBean", rateVO);
	}

	private void loadInitData(RateVO rateVO){
		rateVO.setVendorList(cache.getAllVendorOptions());
		rateVO.setRoleList(cache.getAllRoleOptions());
		rateVO.setLocationList(cache.getAllLocationOptions());
		rateVO.setCurrencyList(cache.getAllCurrencyOptions());
	}

}
